package core;

import picocli.CommandLine.Command;
import picocli.CommandLine.Parameters;
import picocli.CommandLine.Option;
import repository.Branch;
import repository.Repository;

import java.io.File;
import java.util.Arrays;

@Command(name = "branch")
public class JitBranch implements Runnable {
    @Parameters(paramLabel = "<branch name>"
            , description = {"The Branch Name you want to create or delete"}
            , defaultValue = ""
    )
    private String branch_name;

    @Option(names = {"-d", "--delete"})
    boolean isDelete;

    /**
     * 实现了jit branch命令，展示所有本地分支与当前分支，并对输入的分支名称进行创建或删除操作
     */
    @Override
    public void run() {
        if (branch_name.equals("")) {
            String cur = Repository.getInstance().getCurrentBranch().getName();
            File[] files = Repository.getInstance().getRefHeadsPath().toFile().listFiles();
            if (files == null) {
                System.err.println("Invalid path " + Repository.getInstance().getRefHeadsPath().toString());
                System.exit(-1);
            }
            Arrays.stream(files)
                    .forEach(file -> {
                        String name = file.getName();
                        System.out.print(name.equals(cur) ? "* " : "  ");
                        System.out.println(name);
                    });
        } else {
            if (isDelete) {
                delete();
            } else {
                create();
            }
        }
    }

    /**
     * 创建分支，并向暂存区对应文件中写入分支指向的commit的哈希值
     */
    void create() {
        var b = Branch.create(branch_name);
        b.write();
    }

    /**
     * 删除分支，但无法删除当前分支
     */
    void delete() {
        var repo = Repository.getInstance();
        var b = Branch.findByName(branch_name);
        if (b.equals(repo.getCurrentBranch())) {
            System.err.printf("Error: Cannot delete branch '%s' checked out at '%s'%n"
                    , branch_name, repo.getWorkTree().toString());
            System.exit(-1);
        }
        b.delete();
    }
}
